package com.adc.douyu_assistant.client;

import com.adc.douyu_assistant.entity.DanmuMessage;
import com.adc.douyu_assistant.entity.DouyuMessage;
import com.adc.douyu_assistant.utils.ApplicationContextProvider;
import com.adc.douyu_assistant.utils.MessageConstractor;
import com.adc.douyu_assistant.utils.Singleton;
import com.adc.douyu_assistant.utils.Timer;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DouyuAssistantClientHandler extends SimpleChannelInboundHandler<DouyuMessage> {

    private Timer timer;

    private int roomId = 687423;
    private Map<String, DanmuMessage> danmuMessages = new HashMap<>();

    private Map<String, Object> parseContent(String content) {
        Map<String, Object> result = new HashMap<String, Object>();

        String[] dataArrays = content.split("/");

        for (int i = 0; i < dataArrays.length; i++) {
            String tempData = dataArrays[i];
            if (!tempData.isEmpty() && tempData.contains("@=")) {
                int tempDataArraySize = tempData.split("@=").length;
                String key = tempData.split("@=")[0];
                String value = tempDataArraySize > 1 ? tempData.split("@=")[1] : "";

                //如果value值中包含子序列化值，则进行递归分析
//            if(value.contains("@A")){
//                value = ((String)value).replaceAll("@S", "/").replaceAll("@A", "@");
//                value = this.parseContent((String)value);
//            }
                result.put(key, value);
            }
        }
        return result;
    }

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, DouyuMessage message) throws Exception {
        String type = "";
        if (parseContent(message.getMessageContent()).containsKey("type")) {
            type = (String) parseContent(message.getMessageContent()).get("type");
        }
        Channel channel = channelHandlerContext.channel();
        if ("loginres".equals(type)) {
            Singleton.INSTANCE.sendHeartBeatToKeepAlive(channel, 45000);
            timer = ApplicationContextProvider.getBean(Timer.class);
            timer.saveToDB(danmuMessages, 60000);
            return;
        }
        if ("pingreq".equals(type)) {
            String content = "type@=joingroup/rid@=" + roomId + "/gid@=-9999/";
            channel.writeAndFlush(MessageConstractor.getMessage(content));
            return;
        }
        if ("chatmsg".equals(type)) {
            String uid = "";
            String nn = "";
            String txt = "";
            String bnn = "";
            String bl = "";
            if (parseContent(message.getMessageContent()).containsKey("uid")) {
                uid = (String) parseContent(message.getMessageContent()).get("uid");
            }
            if (parseContent(message.getMessageContent()).containsKey("nn")) {
                nn = (String) parseContent(message.getMessageContent()).get("nn");
            }
            if (parseContent(message.getMessageContent()).containsKey("txt")) {
                txt = (String) parseContent(message.getMessageContent()).get("txt");
            }
            if (parseContent(message.getMessageContent()).containsKey("bnn")) {
                bnn = (String) parseContent(message.getMessageContent()).get("bnn");
            }
            if (parseContent(message.getMessageContent()).containsKey("bl")) {
                bl = (String) parseContent(message.getMessageContent()).get("bl");
            }
            if (!nn.isEmpty() && !txt.isEmpty()) {
                ArrayList<String> txts = danmuMessages.containsKey(uid) ? danmuMessages.get(uid).getTxtList() : new ArrayList<>();
                txts.add(txt);
                DanmuMessage danmuMessage = new DanmuMessage(uid, nn, txts, bnn, bl);
                danmuMessages.put(uid, danmuMessage);
                System.out.println(nn + "; " + txt + "; " + bnn + "; " + bl);
            }
        }
//        System.out.println(message.getMessageContent());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String content = "type@=loginreq/roomid@=" + roomId + "/";
        ctx.channel().writeAndFlush(MessageConstractor.getMessage(content));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
